<?php

namespace app\api\controller;

use app\common\logic\Data;
use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class Article extends Base
{
  /**
   * 文章列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function list()
  {
    $rule = [
      'pageNo'  => 'number',
      'title'  => 'chsDash',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 10, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];
    if (!empty($data['title'])) {
      $where['title'] = ['like', '%' . $data['title'] . '%'];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::name('Article')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::name('Article')->where($where)->count('id');
    $articleCate = Db::name('ArticleCate')->field('id,title')->where('status',1)->select()->toArray();
    $artCate = [];
    foreach ($articleCate as $key => $vo) {
      $artCate[$vo['id']] = $vo['title'];
    }
    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d', $vo['create_time']);
      $vo['cate'] = (isset($artCate[$vo['cate_id']]))?$artCate[$vo['cate_id']]:'未知';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  /**
   * 分类列表
   * @return void
   * @author QianLong <87498106@qq.com>
   * @date 2021-04-09 11:36:54
   * @editAuthor QianLong <87498106@qq.com>
   * @editDescription 
   * @editDate 2021-04-09 11:36:54
   */
  public function cate_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'title'  => 'chsDash',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 10, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];
    if (!empty($data['title'])) {
      $where['title'] = ['like', '%' . $data['title'] . '%'];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::name('ArticleCate')->field('*')->where($where)->order('id', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::name('ArticleCate')->where($where)->count('id');
    $articleCate = Db::name('ArticleCate')->field('id,title')->where('status',1)->select()->toArray();
    $artCate = [];
    foreach ($articleCate as $key => $vo) {
      $artCate[$vo['id']] = $vo['title'];
    }
    foreach ($dataList as &$vo) {
      $vo['pid'] = (isset($artCate[$vo['pid']]))?$artCate[$vo['pid']]:'顶级分类';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  /**
   * 所有分类（带层级）
   * @return void
   * @author QianLong <87498106@qq.com>
   * @date 2021-04-09 12:00:42
   * @editAuthor QianLong <87498106@qq.com>
   * @editDescription 
   * @editDate 2021-04-09 12:00:42
   */
  public function all_cate_list()
  {
    $selectResult = Db::name('ArticleCate')->field('id,title,pid,sort')->order('sort','desc')->select()->toArray();
    $sdata = new Data();
    foreach ($selectResult as &$vo) {
      $vo['title'] = $vo['title'];
      $vo['ids'] = join(',', $sdata->getArrSubIds($selectResult, $vo['id']));
    }
    $selectResult = $sdata->arr2table($selectResult);
    return Result::Success($selectResult);
  }
    /**
   * 新增分类数据
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function editCateItem()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|chsDash|max:32',
        'pid|上级分类'  => 'require|number',
        'id|分类ID'  => 'number',
        'status|状态'  => 'require|number',
        'sort|排序'  => 'require|number',
      ];
      $data = [
        'title' => input('param.title', '', 'trim'),
        'id' => input('param.id', '', 'trim'),
        'pid' => input('param.pid', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'sort' => input('param.sort', 0, 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      if (!empty($data['id'])) {
        $status = Db::name('ArticleCate')->where('id',$data['id'])->update($data);
        $tag = '编辑';
      }else{
        unset($data['id']);
        $status = Db::name('ArticleCate')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag.'成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag.'失败，请重试']);
      }
    }else{
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::name('ArticleCate')->where('id',$id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  /**
   * 编辑文章
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function editItemInfo()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|chsDash|max:32',
        'cate_id|分类'  => 'require|number',
        'id|文章ID'  => 'number',
        'status|状态'  => 'require|number',
      ];
      $data = [
        'id' => input('param.id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'cate_id' => input('param.cate_id', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'content' => input('param.content', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      if (!empty($data['id'])) {
        $status = Db::name('Article')->where('id',$data['id'])->update($data);
        $tag = '编辑';
      }else{
        unset($data['id']);
        $data['create_time'] = time();
        $status = Db::name('Article')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag.'成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag.'失败，请重试']);
      }
    }else{
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::name('Article')->where('id',$id)->find();
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  /**
   * 删除
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function delCate()
  {
    $rule = [
      'id'  => 'require|number',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $infoData = Db::name('ArticleCate')->field('id')->where('id', $data['id'])->find();
    if (empty($infoData)) {
      return json(['code' => -1, 'data' => '', 'msg' => '内容不存在或网络异常，请稍后重试']);
    }
    $infoData = Db::name('Article')->where('cate_id', $data['id'])->count();
    if (!empty($infoData)) {
      return json(['code' => -1, 'data' => '', 'msg' => '该分类下存在文章内容，请先删除文章后再操作']);
    }
    $status = Db::name('ArticleCate')->where('id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  /**
   * 删除文章
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function delArt()
  {
    $rule = [
      'id'  => 'require|number',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $infoData = Db::name('Article')->field('id')->where('id', $data['id'])->find();
    if (empty($infoData)) {
      return json(['code' => -1, 'data' => '', 'msg' => '内容不存在或网络异常，请稍后重试']);
    }
    $status = Db::name('Article')->where('id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
}
